package com.zhentao.controller;

import com.zhentao.pojo.*;
import com.zhentao.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

// 添加必要的导入
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhentao.vo.PurchasePageVo;
import com.zhentao.vo.PurchaseInboundPageVo;
import com.zhentao.vo.PurchaseReturnPageVo;

/**
 * 采购订单控制器
 * @date: 2025/8/3 19:33
 * @author: ftt
 */

@RestController
@RequestMapping("purchase")
public class PurchaseController {
    // 注入采购服务
    @Autowired
    private PurchaseOrderService purchaseOrderService;
    @Autowired
    private PurchaseOrderItemService purchaseOrderItemService;
    @Autowired
    private SupplierService supplierService;
    @Autowired
    private ProductService productService;

    // 新注入的服务
    @Autowired
    private PurchaseInboundService purchaseInboundService;
    @Autowired
    private PurchaseInboundItemService purchaseInboundItemService;
    @Autowired
    private WarehouseService warehouseService;

    /**
     * 创建采购订单（支持明细）
     * @param purchaseOrder 采购订单对象，包含items字段
     * @return 创建的采购订单
     */
    @PostMapping
    public PurchaseOrder createPurchase(@RequestBody PurchaseOrder purchaseOrder) {
        // 自动生成订单号（如前端未传递）
        if (purchaseOrder.getOrderNo() == null || purchaseOrder.getOrderNo().trim().isEmpty()) {
            String orderNo = "PO" + new java.text.SimpleDateFormat("yyyyMMddHHmmssSSS").format(new java.util.Date());
            purchaseOrder.setOrderNo(orderNo);
            purchaseOrder.setCreateTime(new java.util.Date());
        }
        purchaseOrderService.save(purchaseOrder);
        // 保存明细
        List<PurchaseOrderItem> items = purchaseOrder.getItems();
        if (items != null && !items.isEmpty()) {
            for (PurchaseOrderItem item : items) {
                item.setOrderId(purchaseOrder.getId());
                purchaseOrderItemService.save(item);
            }
        }
        return purchaseOrder;
    }

    @GetMapping("/supplier")
    public List<Supplier> supplierList(){
        return supplierService.list();
    }
    /**
     * 删除采购订单
     * @param id 采购订单ID
     * @return 是否删除成功
     */
    @DeleteMapping("/{id}")
    public boolean deletePurchase(@PathVariable Long id) {
        // 先删除明细
        purchaseOrderItemService.lambdaUpdate()
                .eq(PurchaseOrderItem::getOrderId, id)
                .remove();
        
        // 再删除主表
        return purchaseOrderService.removeById(id);
    }

    /**
     * 更新采购订单
     * @param purchaseOrder 采购订单对象
     * @return 更新后的采购订单
     */
    @PutMapping
    public PurchaseOrder updatePurchase(@RequestBody PurchaseOrder purchaseOrder) {
        // 获取原有数据，保留创建时间
        PurchaseOrder existingOrder = purchaseOrderService.getById(purchaseOrder.getId());
        if (existingOrder != null) {
            purchaseOrder.setCreateTime(existingOrder.getCreateTime());
        }
        
        // 更新订单主表
        purchaseOrderService.updateById(purchaseOrder);

        // 删除原有明细
        purchaseOrderItemService.lambdaUpdate()
                .eq(PurchaseOrderItem::getOrderId, purchaseOrder.getId())
                .remove();

        // 重新添加明细
        List<PurchaseOrderItem> items = purchaseOrder.getItems();
        if (items != null && !items.isEmpty()) {
            for (PurchaseOrderItem item : items) {
                item.setOrderId(purchaseOrder.getId());
                purchaseOrderItemService.save(item);
            }
        }

        return purchaseOrder;
    }

    /**
     * 从采购订单详情表获取单个采购对象（包含详情）
     * @param id 采购订单ID
     * @return 包含详情的采购订单对象
     */
    @GetMapping("/withDetails/{id}")
    public PurchaseOrder getPurchaseWithDetails(@PathVariable Long id) {
        // 先获取采购订单主信息
        PurchaseOrder purchaseOrder = purchaseOrderService.getById(id);

        if (purchaseOrder != null) {
            Supplier byId1 = supplierService.getById(purchaseOrder.getSupplierId());
            purchaseOrder.setSupplierName(byId1.getName());

            // 获取该订单的所有详情项
            List<PurchaseOrderItem> items = purchaseOrderItemService.lambdaQuery()
                    .eq(PurchaseOrderItem::getOrderId, id)
                    .list();
            // 设置详情项到采购订单对象
            purchaseOrder.setItems(items);
            for (PurchaseOrderItem item : items) {
                Product byId = productService.getById(item.getProductId());
                item.setProductName(byId.getName());
                item.setProductCode(byId.getBarcode());
            }
        }
        return purchaseOrder;
    }

    /**
     * 分页获取采购订单
     * @param purchasePageVo 分页参数
     * @return 分页采购订单列表
     */
    @PostMapping("/page")
    public Page<PurchaseOrder> getPurchasePage(@RequestBody PurchasePageVo purchasePageVo) {
        LambdaQueryWrapper<PurchaseOrder> queryWrapper = Wrappers.<PurchaseOrder>lambdaQuery();

        if (StringUtils.hasText(purchasePageVo.getOrderNo())) {
            queryWrapper.like(PurchaseOrder::getOrderNo, purchasePageVo.getOrderNo());
        }

        if (StringUtils.hasText(purchasePageVo.getSupplierName())) {
            queryWrapper.like(PurchaseOrder::getSupplierName, purchasePageVo.getSupplierName());
        }

        if (StringUtils.hasText(purchasePageVo.getStartDate())) {
            queryWrapper.gt(PurchaseOrder::getOrderDate, purchasePageVo.getStartDate());
        }

        if (StringUtils.hasText(purchasePageVo.getEndDate())) {
            queryWrapper.lt(PurchaseOrder::getOrderDate, purchasePageVo.getEndDate());
        }

        Page<PurchaseOrder> page = purchaseOrderService.page(
                new Page<>(purchasePageVo.getPageNum(), purchasePageVo.getPageSize()),
                queryWrapper
        );

        List<PurchaseOrder> records = page.getRecords();
        for (PurchaseOrder record : records) {
            Supplier byId = supplierService.getById(record.getSupplierId());
            record.setSupplierName(byId.getName());
        }

        return page;
    }

    /**
     * 采购入库操作
     * @param inbound 采购入库单对象
     * @return 入库单对象
     */
    @PostMapping("/inbound")
    public PurchaseInbound createPurchaseInbound(@RequestBody PurchaseInbound inbound) {
        try {
            // 自动生成入库单号（如前端未传递）
            if (inbound.getInboundNo() == null || inbound.getInboundNo().trim().isEmpty()) {
                String inboundNo = "PI" + new java.text.SimpleDateFormat("yyyyMMddHHmmssSSS").format(new java.util.Date());
                inbound.setInboundNo(inboundNo);
            }
            // 设置默认的创建时间
            if (inbound.getCreateTime() == null) {
                inbound.setCreateTime(new java.util.Date());
            }
            // 1. 验证采购订单是否存在
            Long orderId = inbound.getOrderId();
            if (orderId == null) {
                throw new RuntimeException("采购订单ID不能为空");
            }
            PurchaseOrder purchaseOrder = purchaseOrderService.getById(orderId);
            if (purchaseOrder == null) {
                throw new RuntimeException("采购订单不存在");
            }
            // 2. 验证仓库是否存在
            Long warehouseId = inbound.getWarehouseId();
            if (warehouseId == null) {
                throw new RuntimeException("仓库ID不能为空");
            }
            Warehouse warehouse = warehouseService.getById(warehouseId);
            if (warehouse == null) {
                throw new RuntimeException("仓库不存在");
            }
            // 3. 验证入库日期
            if (inbound.getInboundDate() == null) {
                throw new RuntimeException("入库日期不能为空");
            }
            // 4. 保存入库单主表
            purchaseInboundService.save(inbound);
            // 5. 自动从采购订单明细生成入库明细
            List<PurchaseOrderItem> orderItems = purchaseOrderItemService.lambdaQuery().eq(PurchaseOrderItem::getOrderId, orderId).list();
            if (orderItems != null && !orderItems.isEmpty()) {
                for (PurchaseOrderItem orderItem : orderItems) {
                    PurchaseInboundItem inboundItem = new PurchaseInboundItem();
                    inboundItem.setInboundId(inbound.getId());
                    inboundItem.setProductId(orderItem.getProductId());
                    inboundItem.setQuantity(orderItem.getQuantity() != null ? orderItem.getQuantity().setScale(0, java.math.RoundingMode.FLOOR) : null);
                    inboundItem.setUnitPrice(orderItem.getUnitPrice() != null ? orderItem.getUnitPrice().setScale(0, java.math.RoundingMode.FLOOR) : null);
                    inboundItem.setAmount(orderItem.getAmount());
                    inboundItem.setRemark(orderItem.getRemark());
                    purchaseInboundItemService.save(inboundItem);
                }
            }
            // 6. 更新采购订单状态为已入库
            purchaseOrder.setStatus(1);
            purchaseOrderService.updateById(purchaseOrder);
            return inbound;
        } catch (Exception e) {
            throw new RuntimeException("创建采购入库单失败: " + e.getMessage());
        }
    }

    /**
     * 分页获取采购入库单
     * @param inboundPageVo 分页参数
     * @return 分页采购入库单列表
     */
    @PostMapping("/inbound/page")
    public Page<PurchaseInbound> getPurchaseInboundPage(@RequestBody PurchaseInboundPageVo inboundPageVo) {
        LambdaQueryWrapper<PurchaseInbound> queryWrapper = Wrappers.<PurchaseInbound>lambdaQuery();

        if (StringUtils.hasText(inboundPageVo.getInboundNo())) {
            queryWrapper.like(PurchaseInbound::getInboundNo, inboundPageVo.getInboundNo());
        }

        if (inboundPageVo.getOrderId() != null) {
            queryWrapper.eq(PurchaseInbound::getOrderId, inboundPageVo.getOrderId());
        }

        if (StringUtils.hasText(inboundPageVo.getStartDate())) {
            queryWrapper.gt(PurchaseInbound::getInboundDate, inboundPageVo.getStartDate());
        }

        if (StringUtils.hasText(inboundPageVo.getEndDate())) {
            queryWrapper.lt(PurchaseInbound::getInboundDate, inboundPageVo.getEndDate());
        }

        // 排除已存在退货记录的入库单
        if (Boolean.TRUE.equals(inboundPageVo.getExcludeReturned())) {
            List<Long> returnedInboundIds = purchaseReturnService.lambdaQuery()
                    .select(PurchaseReturn::getInboundId)
                    .list()
                    .stream()
                    .map(PurchaseReturn::getInboundId)
                    .filter(Objects::nonNull)
                    .distinct()
                    .collect(Collectors.toList());
            if (returnedInboundIds != null && !returnedInboundIds.isEmpty()) {
                queryWrapper.notIn(PurchaseInbound::getId, returnedInboundIds);
            }
        }

        Page<PurchaseInbound> page = purchaseInboundService.page(
                new Page<>(inboundPageVo.getPageNum(), inboundPageVo.getPageSize()),
                queryWrapper
        );

        List<PurchaseInbound> records = page.getRecords();
        for (PurchaseInbound record : records) {
            // 获取关联的采购订单信息
            PurchaseOrder order = purchaseOrderService.getById(record.getOrderId());
            if (order != null) {
                record.setOrderNo(order.getOrderNo());
            }
            Warehouse byId = warehouseService.getById(record.getWarehouseId());
            if (byId != null) {
                record.setWarehouseName(byId.getName());
            }
        }

        return page;
    }

    @GetMapping("/warehouse")
    public List<Warehouse> warehouseList(){
        return warehouseService.list();
    }

    /**
     * 获取采购入库单详情（包含明细）
     * @param id 采购入库单ID
     * @return 包含详情的采购入库单对象
     */
    @GetMapping("/inbound/withDetails/{id}")
    public PurchaseInbound getPurchaseInboundWithDetails(@PathVariable Long id) {
        // 先获取采购入库单主信息
        PurchaseInbound purchaseInbound = purchaseInboundService.getById(id);

        if (purchaseInbound != null) {
            // 获取关联的采购订单信息
            PurchaseOrder order = purchaseOrderService.getById(purchaseInbound.getOrderId());
            if (order != null) {
                purchaseInbound.setOrderNo(order.getOrderNo());
            }

            // 获取仓库信息
            Warehouse warehouse = warehouseService.getById(purchaseInbound.getWarehouseId());
            if (warehouse != null) {
                purchaseInbound.setWarehouseName(warehouse.getName());
            }

            // 获取该入库单的所有详情项
            List<PurchaseInboundItem> items = purchaseInboundItemService.lambdaQuery()
                    .eq(PurchaseInboundItem::getInboundId, id)
                    .list();
            // 设置详情项到采购入库单对象
            purchaseInbound.setItems(items);
            for (PurchaseInboundItem item : items) {
                PurchaseInbound byId = purchaseInboundService.getById(item.getInboundId());
                Product byId1 = productService.getById(item.getProductId());
                if (byId != null && byId1 != null) {
                    item.setInboundNo(byId.getInboundNo());
                    item.setWarehouseName(byId.getWarehouseName());
                    item.setInboundDate(byId.getInboundDate());
                    item.setProductName(byId1.getName());
                    item.setProductCode(byId1.getBarcode());
                }
            }
        }
        return purchaseInbound;
    }

    /**
     * 更新采购入库单
     * @param purchaseInbound 采购入库单对象
     * @return 更新后的采购入库单
     */
    @PutMapping("/inbound")
    public PurchaseInbound updatePurchaseInbound(@RequestBody PurchaseInbound purchaseInbound) {
        // 获取原有数据，保留创建时间
        PurchaseInbound existingInbound = purchaseInboundService.getById(purchaseInbound.getId());
        if (existingInbound != null) {
            purchaseInbound.setCreateTime(existingInbound.getCreateTime());
        }
        
        // 更新入库单主表
        purchaseInboundService.updateById(purchaseInbound);

        // 删除原有明细
        purchaseInboundItemService.lambdaUpdate()
                .eq(PurchaseInboundItem::getInboundId, purchaseInbound.getId())
                .remove();

        // 重新添加明细
        List<PurchaseInboundItem> items = purchaseInbound.getItems();
        if (items != null && !items.isEmpty()) {
            for (PurchaseInboundItem item : items) {
                item.setInboundId(purchaseInbound.getId());
                purchaseInboundItemService.save(item);
            }
        }

        return purchaseInbound;
    }

    /**
     * 删除采购入库单
     * @param id 采购入库单ID
     * @return 是否删除成功
     */
    @DeleteMapping("/inbound/{id}")
    public boolean deletePurchaseInbound(@PathVariable Long id) {
        // 先删除明细
        purchaseInboundItemService.lambdaUpdate()
                .eq(PurchaseInboundItem::getInboundId, id)
                .remove();

        // 再删除主表
        return purchaseInboundService.removeById(id);
    }

    // 注入采购退货相关服务
    @Autowired
    private PurchaseReturnService purchaseReturnService;
    @Autowired
    private PurchaseReturnItemService purchaseReturnItemService;

    /**
     * 创建采购退货单
     * @param purchaseReturn 采购退货单对象
     * @return 创建的采购退货单
     */
    @PostMapping("/return")
    public PurchaseReturn createPurchaseReturn(@RequestBody PurchaseReturn purchaseReturn) {
        // 1. 验证采购入库单是否存在
        Long inboundId = purchaseReturn.getInboundId();
        PurchaseInbound purchaseInbound = purchaseInboundService.getById(inboundId);
        if (purchaseInbound == null) {
            throw new RuntimeException("采购入库单不存在");
        }

        // 1.1 校验该入库单是否已存在退货单，存在则不允许重复创建
        long existsCount = purchaseReturnService.lambdaQuery()
                .eq(PurchaseReturn::getInboundId, inboundId)
                .count();
        if (existsCount > 0) {
            throw new RuntimeException("该入库单已存在退货单，不可重复创建");
        }

        // 2. 自动生成退货单号（如前端未传递）
        if (purchaseReturn.getReturnNo() == null || purchaseReturn.getReturnNo().trim().isEmpty()) {
            String returnNo = "PR" + new java.text.SimpleDateFormat("yyyyMMddHHmmssSSS").format(new java.util.Date());
            purchaseReturn.setReturnNo(returnNo);
        }

        // 3. 设置创建时间和默认状态
        if (purchaseReturn.getCreateTime() == null) {
            purchaseReturn.setCreateTime(new java.util.Date());
        }
        if (purchaseReturn.getStatus() == null) {
            purchaseReturn.setStatus(0); // 默认草稿状态
        }

        // 4. 确保仓库ID正确设置（从入库单获取）
        if (purchaseReturn.getWarehouseId() == null) {
            purchaseReturn.setWarehouseId(purchaseInbound.getWarehouseId());
        }

        // 5. 保存退货单主表
        purchaseReturnService.save(purchaseReturn);

        // 6. 处理退货单明细
        return getPurchaseReturn(purchaseReturn);
    }

    /**
     * 分页获取采购退货单
     * @param returnPageVo 分页参数
     * @return 分页采购退货单列表
     */
    @PostMapping("/return/page")
    public Page<PurchaseReturn> getPurchaseReturnPage(@RequestBody PurchaseReturnPageVo returnPageVo) {
        LambdaQueryWrapper<PurchaseReturn> queryWrapper = Wrappers.<PurchaseReturn>lambdaQuery();

        if (StringUtils.hasText(returnPageVo.getReturnNo())) {
            queryWrapper.like(PurchaseReturn::getReturnNo, returnPageVo.getReturnNo());
        }

        if (returnPageVo.getInboundId() != null) {
            queryWrapper.eq(PurchaseReturn::getInboundId, returnPageVo.getInboundId());
        }

        if (StringUtils.hasText(returnPageVo.getStartDate())) {
            queryWrapper.gt(PurchaseReturn::getReturnDate, returnPageVo.getStartDate());
        }

        if (StringUtils.hasText(returnPageVo.getEndDate())) {
            queryWrapper.lt(PurchaseReturn::getReturnDate, returnPageVo.getEndDate());
        }

        Page<PurchaseReturn> page = purchaseReturnService.page(
                new Page<>(returnPageVo.getPageNum(), returnPageVo.getPageSize()),
                queryWrapper
        );

        List<PurchaseReturn> records = page.getRecords();
        for (PurchaseReturn record : records) {
            // 获取关联的采购入库单信息
            PurchaseInbound inbound = purchaseInboundService.getById(record.getInboundId());
            if (inbound != null) {
                record.setInboundNo(inbound.getInboundNo());
            }
            Warehouse byId = warehouseService.getById(record.getWarehouseId());
            if (byId != null) {
                record.setWarehouseName(byId.getName());
            }
        }

        return page;
    }

    /**
     * 获取采购退货单详情（包含明细）
     * @param id 采购退货单ID
     * @return 包含详情的采购退货单对象
     */
    @GetMapping("/return/withDetails/{id}")
    public PurchaseReturn getPurchaseReturnWithDetails(@PathVariable Long id) {
        // 先获取采购退货单主信息
        PurchaseReturn purchaseReturn = purchaseReturnService.getById(id);

        if (purchaseReturn != null) {
            // 获取关联的采购入库单信息
            PurchaseInbound inbound = purchaseInboundService.getById(purchaseReturn.getInboundId());
            if (inbound != null) {
                purchaseReturn.setInboundNo(inbound.getInboundNo());
                purchaseReturn.setOrderNo(inbound.getOrderNo());
            }

            // 获取仓库信息
            Warehouse warehouse = warehouseService.getById(purchaseReturn.getWarehouseId());
            if (warehouse != null) {
                purchaseReturn.setWarehouseName(warehouse.getName());
            }

            // 获取该退货单的所有详情项
            List<PurchaseReturnItem> items = purchaseReturnItemService.lambdaQuery()
                    .eq(PurchaseReturnItem::getReturnId, id)
                    .list();
            // 设置详情项到采购退货单对象
            purchaseReturn.setItems(items);
            for (PurchaseReturnItem item : items) {
                PurchaseReturn byId = purchaseReturnService.getById(item.getReturnId());
                Product byId1 = productService.getById(item.getProductId());
                if (byId != null && byId1 != null) {
                    item.setReturnNo(byId.getReturnNo());
                    item.setWarehouseName(byId.getWarehouseName());
                    item.setReturnDate(byId.getReturnDate());
                    item.setProductName(byId1.getName());
                    item.setProductCode(byId1.getBarcode());
                }
            }
        }
        return purchaseReturn;
    }

    /**
     * 更新采购退货单
     * @param purchaseReturn 采购退货单对象
     * @return 更新后的采购退货单
     */
    @PutMapping("/return")
    public PurchaseReturn updatePurchaseReturn(@RequestBody PurchaseReturn purchaseReturn) {
        // 获取原有数据，保留创建时间
        PurchaseReturn existingReturn = purchaseReturnService.getById(purchaseReturn.getId());
        if (existingReturn != null) {
            purchaseReturn.setCreateTime(existingReturn.getCreateTime());
        }
        
        // 更新退货单主表
        purchaseReturnService.updateById(purchaseReturn);

        // 删除原有明细
        purchaseReturnItemService.lambdaUpdate()
                .eq(PurchaseReturnItem::getReturnId, purchaseReturn.getId())
                .remove();

        // 重新添加明细
        return getPurchaseReturn(purchaseReturn);
    }

    private PurchaseReturn getPurchaseReturn(@RequestBody PurchaseReturn purchaseReturn) {
        List<PurchaseReturnItem> items = purchaseReturn.getItems();
        if (items != null && !items.isEmpty()) {
            for (PurchaseReturnItem item : items) {
                item.setReturnId(purchaseReturn.getId());
                purchaseReturnItemService.save(item);
            }
        }

        return purchaseReturn;
    }

    /**
     * 删除采购退货单
     * @param id 采购退货单ID
     * @return 是否删除成功
     */
    @DeleteMapping("/return/{id}")
    public boolean deletePurchaseReturn(@PathVariable Long id) {
        // 先删除明细
        purchaseReturnItemService.lambdaUpdate()
                .eq(PurchaseReturnItem::getReturnId, id)
                .remove();

        // 再删除主表
        return purchaseReturnService.removeById(id);
    }
}
